package com.piece.core.verifycode.factory.captcha;

import com.google.code.kaptcha.Producer;
import com.piece.core.framework.constant.ApplicationConstants;
import com.piece.core.framework.constant.ParamConstants;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.properties.ApplicationProperties;
import com.piece.core.verifycode.enums.CaptchaType;
import com.piece.core.verifycode.factory.ValidateCode;
import com.piece.core.verifycode.processor.AbstractValidateCodeProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * 验证码处理器
 */
@Slf4j
@Component("captchaValidateCodeProcessor")
public class CaptchaValidateCodeProcessor extends AbstractValidateCodeProcessor<ValidateCode> {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Resource(name = "defaultCaptcha")
    private Producer defaultCaptcha;

    @Resource(name = "defaultMathCaptcha")
    private Producer defaultMathCaptcha;

    @Override
    public void send(HttpServletRequest request, HttpServletResponse response, ValidateCode validateCode) throws Exception {
        ServletOutputStream out = null;
        try {
            request.setCharacterEncoding("utf-8");
            response.reset();
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            //response.setHeader("Access-Control-Allow-Origin", request.getHeader("HTTP_ORIGIN"));
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("image/jpeg");

            String type = request.getParameter(ParamConstants.CAPTCHA_TYPE);
            if (StringUtil.isEmpty(type)) {
                type = Convert.toStr(applicationProperties.getValue(ApplicationConstants.KAPTCHA_TYPE), "char");
            }
            BufferedImage bi;
            if (CaptchaType.MATH.name().equals(type)) {
                bi = defaultMathCaptcha.createImage(validateCode.getCode());
            } else {
                bi = defaultCaptcha.createImage(validateCode.getCode());
            }
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } catch (Exception e) {
            log.error("生成验证码异常：{}", e.getMessage());
        } finally {
            if (null != out) {
                out.close();
            }
        }
    }
}
